package com.yu.client;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import javax.xml.namespace.QName;
import javax.xml.ws.BindingProvider;
import javax.xml.ws.Service;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * @author : wenchao.long
 * @date : Created in 2021/01/05 14:29 周二
 * @description :
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
public class SoapClient {
    private String wsdl;

    private String nameSpaceUrl;

    private String localPart;

    private boolean requireAuth = false;

    private String username;

    private String password;

    public SoapClient(String wsdl, String nameSpaceUrl, String localPart) {
        this.wsdl = wsdl;
        this.nameSpaceUrl = nameSpaceUrl;
        this.localPart = localPart;
    }

    /**
     * 创建service实例
     *
     * @param serviceInterface serviceInterface
     * @param <T>              T
     * @return T
     * @throws MalformedURLException MalformedURLException
     */
    public <T> T creatServiceInstance(Class<T> serviceInterface) throws MalformedURLException {
        URL url = new URL(wsdl);
        QName qName = new QName(nameSpaceUrl, localPart);
        Service service = Service.create(url, qName);
        T port = service.getPort(serviceInterface);
        if (requireAuth) {
            BindingProvider prov = (BindingProvider) port;
            prov.getRequestContext().put(BindingProvider.USERNAME_PROPERTY, username);
            prov.getRequestContext().put(BindingProvider.PASSWORD_PROPERTY, password);
        }
        return port;
    }
}
